package com.broada.apm.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;

import com.broada.apm.ajax.Result;
import com.broada.apm.ajax.ServerResult;
import com.broada.apm.base.BaseService;
import com.broada.apm.entity.L7Module;
import com.broada.apm.entity.NoticeCommandException;
import com.broada.apm.entity.PacketCapture;
import com.broada.apm.entity.SSLCertificate;
import com.broada.apm.entity.Service;
import com.broada.apm.entity.ServiceLua;
import com.broada.apm.entity.ServiceProtocol;
import com.broada.apm.indicator.api.AnalyzerService;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.indicator.api.common.ServiceNotExistException;
import com.broada.apm.model.Analyzer;
import com.broada.apm.model.LuaSettings;
import com.broada.apm.model.PerformanceView;
import com.broada.apm.protocol.ZeroClient;
import com.broada.apm.service.ServerService;
import com.broada.apm.util.LicUtils;
import com.broada.apm.util.PacketCaptureManager;
import com.broada.apm.utils.ApmFileUtils;
import com.broada.apm.utils.ExceptionUtils;
import com.broada.apm.utils.IPUtils;

import groovy.json.JsonBuilder;

public class ServerServiceImpl extends BaseService implements ServerService {
	private static final String SSL_PATH = "../ssl/";
	private static final int KEEP = 0;
	private static final int UP = 1;
	private static final int DOWN = 2;
//	private static final int[] severity = {50, 20, 10};
	private static final String DEFAULT = "default";
	private Logger logger = LoggerFactory.getLogger(ServerServiceImpl.class);
	
	@Autowired
	private AnalyzerService analyzerService;
	
	@Override
	public ServerResult queryDiscoveryServices(String keyWord, String serviceId, String direction, String appId, 
			int pageSize, int pageIndex, String orderBy, boolean desc) {
		keyWord = decoderString(keyWord);
		ServerResult result = new ServerResult();
		try {
			List<Service> services = serverLogic.queryDisServiceByCondition(keyWord, serviceId, direction, appId, orderBy, desc);
			result.setNodesPage(pageSize > 0 ? pageSize : 100, pageIndex, services);
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(logger, "queryDisServiceByCondition 失败", e);
			result.setFailMessage("查询业务组件失败");
		}

		return result;
	}

	@Override
	public ServerResult queryServiceById(String nodeId) {
		ServerResult result = new ServerResult();
		Service service = serverLogic.queryServiceById(nodeId);
		result.setNode(service);
		return result;
	}

	@Override
	public ServerResult deleteService(String nodeId){
		ServerResult result = new ServerResult();
		if (StringUtils.isNotBlank(nodeId)) {
			try {
				serverLogic.deleteServiceById(nodeId);
			} catch (Exception e) {
				ExceptionUtils.error(logger, "deleteService 失败", e);
				result.setFailMessage("删除业务组件失败");
			}
		}
		return result;
	}

	@Override
	public ServerResult saveService(Service service) {
		ServerResult result = new ServerResult();
		if (service != null) {
			try {
				serverLogic.saveService(service);
			} catch (Exception e) {
				ExceptionUtils.error(logger, "saveService 失败", e);
				result.setFailMessage("保存业务组件失败");
			}
		}
		return result;
	}

	@Override
	public ServerResult updateServiceName(String nodeId, Service service) {
		ServerResult result = new ServerResult();
		if (service == null || StringUtils.isBlank(nodeId)) {
			result.setFailMessage("参数错误");
			return result;
		}
		service.setId(nodeId);
		try {
			serverLogic.updateServiceName(service);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage("设置节点名称失败");
		} catch (ServiceNotExistException e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ServerResult updateServiceProtocol(ServiceProtocol sp) {
		ServerResult result = new ServerResult();

		Service ser = new Service();
		ser.setId(sp.getService_id());
		ser.setProtocol(sp.getL7_proto());
		Service service = null;
		try {
			service = serverLogic.updateServiceProtocol(ser);
		} catch (NoticeCommandException e) {
			ExceptionUtils.error(logger, "通知Indicator模块异常", e);
			result.setFailMessage("通知Indicator模块异常");
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(logger, "修改节点协议失败", e);
			result.setFailMessage("修改节点协议失败");
		}
		if (service == null)
			result.setFailMessage("协议保存失败.");
		result.setNode(service);
		return result;
	}

	@Override
	public ServerResult deleteDiscoveryService(String id) {
		ServerResult result = new ServerResult();
		if (StringUtils.isBlank(id)) {
			result.setFailMessage("参数错误");
			return result;
		}
		try {
			serverLogic.deleteDiscoveryService(id);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(logger, "删除业务组件失败！", e);
		}

		return result;
	}

	@Override
	public String licreq(HttpServletRequest request, HttpServletResponse response, String consumer) throws Exception {
		if (StringUtils.isEmpty(consumer)) {
			return "客户名称不允许为空.";
		}
		String reqtext = LicUtils.req(consumer);
		response.setContentType("application/x-msdownload");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String("BroadviewAPM.req"
				.getBytes("gbk"), "iso-8859-1"));
		response.getOutputStream().print(reqtext);
		response.getOutputStream().flush();
		response.flushBuffer();
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ServerResult licimport(HttpServletRequest request, HttpServletResponse response)  {
		PrintWriter out = null;
		ServerResult ret = new ServerResult();
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			// 验证一个正确许可
			DiskFileItemFactory df = new DiskFileItemFactory();
			ServletFileUpload sf = new ServletFileUpload(df);
			File tempFile = FileUtils.getTempDirectory();
			if (!tempFile.exists())
				tempFile.mkdirs();
			df.setRepository(tempFile);
			sf.setFileSizeMax(1024 * 1024 * 100);// 上传文件最大为100M
			List<FileItem> list = null;
			try {
				list = sf.parseRequest(request);
			} catch (FileUploadException e) {
				ExceptionUtils.error(logger, "licimport失败", e);
			}
			
			if (list==null || list.size() != 1) {
				ret.setFailMessage("没有找到上传的lic文件");
				return ret;
			}
			
			FileItem f = list.get(0);
			String liccontent = f.getString();
			String result = LicUtils.importLic(liccontent);
			if (result != null) {
				ret.setFailMessage(result);
				out.println("<script>parent.APM.iframeCallback(2,0,'" + result + "');</script>");
				return ret;
			} else {
				out.println("<script>parent.APM.iframeCallback(1,0,'');</script>");
			}
		} catch (Exception e) {
			out.println("<script>parent.APM.iframeCallback(2,0,'" + e.getMessage() + "');</script>");
			logger.error("导入文件,出现异常！", e.getMessage());
			ret.setFailMessage("导入文件失败,出现异常！");
		} finally {
			out.flush();
			out.close();
		}
		return ret;
	}

	@Override
	public ServerResult saveLuaScript(ServiceLua serviceLua) {
		ServerResult result = new ServerResult();
		if (serviceLua == null) {
			result.setFailMessage("参数错误");
			return result;
		}
		Service service = new Service();
		String serviceId = serviceLua.getServiceId();
		String[] serviceIds = null;
		if(serviceId.contains("[")){
			if(serviceId.length() > 1 && serviceId.length() <= 4){
				result.setFailMessage("服务节点信息错误");
				return result;
			}
			serviceIds = serviceId.substring(1, serviceId.length()-1).split(",");
		}else{
			serviceIds = (String[]) Arrays.asList(serviceId).toArray();
		}
		if(serviceIds.length > 0){
			if(serviceIds.length != 1 || serviceIds[0].contains("\"")){
				// 批量 id为 "id"
				for(String id : serviceIds){
					service.setId(id.substring(1, id.length()-1));
					service.setLua(serviceLua.getLua());
					try {
						serverLogic.updateServiceLua(service);
					} catch (Exception e) {
						result.setInvalidMessage(e.getMessage());
					}
				}
			}else{
				// 单个节点设置
				service.setId(serviceIds[0]);
				service.setLua(serviceLua.getLua());
				try {
					serverLogic.updateServiceLua(service);
				} catch (Exception e) {
					result.setInvalidMessage(e.getMessage());
				}
			}
		}else{
			result.setFailMessage("服务节点信息错误");
			return result;
		}
		return result;
	}

	@Override
	public String saveSSLCertificate(String serviceId,String sslType, String sslPwd, String callBack, HttpServletRequest request,
			HttpServletResponse response) {
		String returnResult = "<script>" + callBack + "(";
		ServerResult result = new ServerResult();
		if (serviceId == null) {
			result.setFailMessage("参数错误");
			JsonBuilder json = new JsonBuilder(result);
			returnResult += json + ")</script>";
			return returnResult;
		}

		// 文件上传
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			try {
				//读取文件
				File file = createFile(request, serviceId);
				byte[] privateKeyFile = FileCopyUtils.copyToByteArray(file);
				
				SSLCertificate sslCertificate = new SSLCertificate();
				sslCertificate.setServiceId(serviceId);
				sslCertificate.setSslPwd(sslPwd);
				sslCertificate.setSslType(sslType);
				sslCertificate.setPrivateKey(privateKeyFile);
				
				//先通知协议分析器端，如果没有异常抛出则存库
				Service service = serverLogic.queryDisServiceById(serviceId);
				List<Analyzer> analyzers = analyzerService.getAllAnalyzerNoPage();
				if(analyzers != null && analyzers.size() > 0){
					String addr = "";
					for(Analyzer analyzer:analyzers){
						addr = "tcp://" + analyzer.getIp() + ":" + analyzer.getPort();
						try(ZeroClient client = new ZeroClient()){
							client.connect(addr);
							client.ssl_setup(IPUtils.toLittleEndianInteger(service.getIp()), service.getPort(), file.getAbsolutePath(), sslPwd);
						} catch (Exception e) {
							throw e;
						}
					}
				}
				serverLogic.saveSSLCertificate(sslCertificate);
				file.delete();
			} catch (Exception e) {
				ExceptionUtils.error(logger, "SSL证书设定异常", e);
				result.setFailMessage(e.getMessage());
			}
		}

		JsonBuilder json = new JsonBuilder(result);
		returnResult += json + ")</script>";
		return returnResult;
	}
	
	private File createFile(HttpServletRequest request, String serviceId) throws Exception {
		DiskFileItemFactory df = new DiskFileItemFactory();
		// 设定阀值1M，如果超过这个值，则文件就直接写到临时文件，不会一直占用内存
		// 利用这个特性可在上传大文件的时候不会占用大量内存，可以提高并发使用量。
		df.setSizeThreshold(1024 * 1024);
		File tempFile = FileUtils.getTempDirectory();
		if (!tempFile.exists())
			tempFile.mkdirs();
		df.setRepository(tempFile);
		ServletFileUpload upload = new ServletFileUpload(df);

		File file = null;
		@SuppressWarnings("unchecked")
		List<FileItem> list = upload.parseRequest(request);
		File sslPath = ApmFileUtils.getFile(SSL_PATH);
		if (!sslPath.exists())
			sslPath.mkdir();
		String filePath = SSL_PATH + serviceId +"/";
		File sslDir = ApmFileUtils.getFile(filePath);
		if (!sslDir.exists())
			sslDir.mkdir();
		for (int i = 0; i < list.size(); i++) {
			FileItem fileItem = (FileItem) list.get(i);
			String fileName = fileItem.getName();
			if (StringUtils.isBlank(fileName)) {
				throw new Exception("没有文件上传");
			}
			file = ApmFileUtils.getFile(filePath + fileName);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			fileItem.write(file);
		}
		return file;
	}

	@Override
	public ServerResult packetCapture(String serviceId, int time) {
		ServerResult result = new ServerResult();
		try {
			PacketCapture packetCapture = new PacketCapture();
			Service service = serverLogic.queryServiceById(serviceId);
			if (service == null)
				throw new ApmDataIndicatorException("业务节点不存在");
			packetCapture.setHost(service.getIp());
			packetCapture.setTimes(time);
			String packetDumpId = PacketCaptureManager.packetCapture(packetCapture);
			result.addData("packetDumpId", packetDumpId);
		} catch (ApmDataIndicatorException | IOException e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ServerResult querySSLByServiceId(String serviceId) {
		ServerResult result = new ServerResult();
		try {
			SSLCertificate sslCertificate = serverLogic.querySSLByServiceId(serviceId);
			result.setSSLCeritficate(sslCertificate);
		} catch (Exception e) {
			result.setInvalidMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ServerResult deleteSSLCertificate(String serviceId) {
		ServerResult result = new ServerResult();
		if (StringUtils.isNotBlank(serviceId)) {
			try {
				SSLCertificate sslCertificate = serverLogic.querySSLByServiceId(serviceId);
				if (sslCertificate == null) {
					result.setFailMessage("SSL证书已删除");
					return result;
				}
				
				//通知协议分析器端
				Service service = serverLogic.queryDisServiceById(serviceId);
				List<Analyzer> analyzers = analyzerService.getAllAnalyzerNoPage();
				if(analyzers != null && analyzers.size() > 0){
					String addr = "";
					for(Analyzer analyzer:analyzers){
						addr = "tcp://" + analyzer.getIp() + ":" + analyzer.getPort();
						try(ZeroClient client = new ZeroClient()){
							client.connect(addr);
							client.ssl_setup(IPUtils.toLittleEndianInteger(service.getIp()), service.getPort(), null, sslCertificate.getSslPwd());
						} catch (Exception e) {
							throw e;
						}
					}
				}
				serverLogic.deleteSSLCertificate(serviceId);
			} catch (Exception e) {
				ExceptionUtils.error(logger, "SSL删除设定异常", e);
				result.setFailMessage("SSL删除设定异常");
			}
		}
		return result;
	}

	@Override
	public ServerResult queryLuaScriptByServiceId(String serviceId) {
		ServerResult result = new ServerResult();
		try {
			ServiceLua luaScript = serverLogic.queryLuaScriptByServiceId(serviceId);
			result.setLuaScript(luaScript);
		} catch (Exception e) {
			result.setInvalidMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ServerResult queryService(String ip, String port, String serviceType, int focus, int serverity, long startDate, long endDate, String sortBy, boolean desc, int pageSize, int pageIndex) {
		long startTime1 = System.currentTimeMillis();
		ServerResult result = new ServerResult();
		if ("NaN".equals(startDate) || "NaN".equals(endDate)) {
			result.setFailMessage("查询时间错误");
			return result;
		}
		if (endDate == 0)
			endDate = System.currentTimeMillis();
		if (startDate == 0)
			startDate = endDate - 60 * 60 * 1000;

		Service service = new Service();
		service.setIp(ip);
		if(StringUtils.isNotBlank(port)){
			service.setPort(Integer.valueOf(port));
		}
		if (focus == 1) {
			service.setFocus(focus);
		}
		
		try {
			String sortByMysql = "ip";
			boolean sortDirec = false;
			List<Service> allServices = serverLogic.getDisServiceFocusOrNot(service, serviceType, sortByMysql, sortDirec, Integer.MAX_VALUE, 0, serverity, new Date(startDate), new Date(endDate));
			// 需要返回的服务节点
			List<Service> services = new ArrayList<Service>();
			if (pageIndex < allServices.size() - 1) {
				services = allServices.subList(pageIndex * pageSize, (pageIndex + 1) * pageSize);
			} else {
				services = allServices.subList((allServices.size() - 1) * pageSize, allServices.size());
			}
			Map<String, Service> servIdMap = new HashMap<String, Service>();
			List<String> servIds = new ArrayList<String>();
			for (Service serv : services) {
				servIds.add(serv.getId());
				servIdMap.put(serv.getName(), serv);
			}
			if (servIdMap.size() == 0) {
				return result;
			}
			
			if (StringUtils.isNotBlank(sortBy)) {
				sortByMysql = StringUtils.isNotBlank(sortByMysql) ? null : sortBy;
			}
			// ES 查询耗时
			long startTime = System.currentTimeMillis();
			List<PerformanceView> perfs = servicePerformanceLogic.getServicePerformances(ip, serviceType, focus, serverity, startDate, endDate, servIdMap.keySet());
			logger.info("服务节点ES查询耗时：" + (System.currentTimeMillis() - startTime));
			// 当数据取的是当前一分钟的数据时，需要对比前一分钟
			Map<String, Map<String, Object>> contrastMap = new HashMap<String, Map<String, Object>>();
			// 节点是否有告警，告警等级
			Map<String, Map<String, Object>> serviceSeverityMap = new HashMap<String, Map<String, Object>>();
			
			// 只有已关注节点需要对比性能数据以及告警等级
			Map<String, PerformanceView> perfServiceMap = new HashMap<String, PerformanceView>();
			if (focus == 1) {
				startTime = System.currentTimeMillis();
				if (endDate - startDate == 60 * 1000) {
					// 上一分钟性能
					List<PerformanceView> lastPerfs = servicePerformanceLogic.getServicePerformances(ip, serviceType, focus,
							serverity, startDate - 60 * 1000, endDate - 60 * 1000, servIdMap.keySet());
					Map<String, PerformanceView> lastMap = new HashMap<String, PerformanceView>();
					for (PerformanceView lastPerf : lastPerfs) {
						lastMap.put(lastPerf.getServiceId(), lastPerf);
					}
					if (serverity == 0) {
						// 这一分钟告警等级
						Map<String, Map<String, Object>> serivceSeverityMap = alertLogic.queryAlertByServiceAndSeverity(servIds, new Date(startDate), new Date(endDate), 0);
						for (PerformanceView perf : perfs) {
							Map<String, Object> map = new HashMap<String, Object>();
							if (lastMap.get(perf.getServiceId()) != null) {
								map = setCompareResult(perf, lastMap.get(perf.getServiceId()));
								contrastMap.put(perf.getServiceId(), map);
							}
							perfServiceMap.put(perf.getServiceId(), perf);
						}
						for (String id : servIds) {
							Map<String, Object> map = contrastMap.get(id);
							if (map == null) {
								map = new HashMap<String, Object>();
								contrastMap.put(id, map);
							}
							if (serivceSeverityMap.get(id) != null) {
								map.put("severity", serivceSeverityMap.get(id).get("severity"));
							}
						}
					} else {
						for (PerformanceView perf : perfs) {
							Map<String, Object> map = new HashMap<String, Object>();
							if (lastMap.get(perf.getServiceId()) != null) {
								map = setCompareResult(perf, lastMap.get(perf.getServiceId()));
								contrastMap.put(perf.getServiceId(), map);
							}
							perfServiceMap.put(perf.getServiceId(), perf);
						}
						for (String id : servIds) {
							Map<String, Object> map = contrastMap.get(id);
							if (map == null) {
								map = new HashMap<String, Object>();
								contrastMap.put(id, map);
							}
							map.put("severity", serverity);
						}
					}
				} else {
					// 这一分钟告警等级
					if (serverity == 0) {
						Map<String, Map<String, Object>> serivceSeverityMap = alertLogic.queryAlertByServiceAndSeverity(servIds, new Date(startDate), new Date(endDate), 0);
						for (PerformanceView perf : perfs) {
							Map<String, Object> map = new HashMap<String, Object>();
							if (serivceSeverityMap.get(perf.getServiceId()) != null) {
								map.put("severity", serivceSeverityMap.get(perf.getServiceId()).get("severity"));
								contrastMap.put(perf.getServiceId(), map);
							}
							perfServiceMap.put(perf.getServiceId(), perf);
						}
						for (String id : servIds) {
							Map<String, Object> map = contrastMap.get(id);
							if (map == null) {
								map = new HashMap<String, Object>();
								contrastMap.put(id, map);
							}
							if (serivceSeverityMap.get(id) != null) {
								map.put("severity", serivceSeverityMap.get(id).get("severity"));
							}
						}
					} else {
						for (String id : servIds) {
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("severity", serverity);
							contrastMap.put(id, map);
						}
						for (PerformanceView perf : perfs) {
							perfServiceMap.put(perf.getServiceId(), perf);
						}
					}
				}
				logger.info("服务节点对比性能数据查询耗时：" + (System.currentTimeMillis() - startTime));
			} else {
				for (PerformanceView perf : perfs) {
					perfServiceMap.put(perf.getServiceId(), perf);
				}
			}
			
			List<Service> servicePerfs = new ArrayList<Service>();
			// 排序，先排MySQL还是先排ES
			startTime = System.currentTimeMillis();
			for (String id : servIds) {
				if (perfServiceMap.isEmpty() || !perfServiceMap.keySet().contains(id)) {
					addService(servicePerfs, null, servIdMap.get(id), contrastMap, serviceSeverityMap);
				} else {
					addService(servicePerfs, perfServiceMap.get(id), servIdMap.get(id), contrastMap,
							serviceSeverityMap);
				}
			}
			logger.info("服务节点排序耗时：" + (System.currentTimeMillis() - startTime));
			result.setNodesPage(pageSize > 0 ? pageSize : 10, pageIndex, allServices);
			result.put("nodes", servicePerfs);
		} catch(Exception e) {
			logger.error(e.getMessage());
			result.setFailMessage("查询服务节点信息异常");
		}
		logger.info("服务节点总耗时：" + (System.currentTimeMillis() - startTime1));
		return result;
	}

	@Override
	public ServerResult serviceFocusOnOrNot(String serviceId, Service service) {
		ServerResult result = new ServerResult();
		try {
			Service ser = serverLogic.queryDisServiceById(serviceId);
			if (ser == null) {
				result.setFailMessage("节点不存在");
				return result;
			}
			service.setId(serviceId);
			// 取消关注节点，删除其SSL证书和Lua脚本
			if (service.getFocus() == 0) {
				alertLogic.deleteThresholdsByTargetId(DEFAULT, serviceId, "threshold", null);
				alertLogic.deleteThresholdsByTargetId(DEFAULT, serviceId, "algorithm", "system");
				alertLogic.deleteThresholdsByTargetId(DEFAULT, serviceId, "algorithm", "business");
				deleteSSLCertificate(serviceId);
				ser.setLua(null);
				serverLogic.updateServiceLua(ser);
			}
			ser.setFocus(service.getFocus());
			serverLogic.updateDisService(ser);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setFailMessage("关注或取消关注服务节点失败");
		}
		return result;
	}

	@Override
	public ServerResult queryServiceFocusCount() {
		ServerResult result = new ServerResult();
		try {
			Map<String, Object> map = serverLogic.queryServiceFocusCount();
			result.setServiceFocusCount(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setFailMessage("服务节点个数统计失败");
		}
		return result;
	}

	@Override
	public ServerResult setServiceName(String nodeId, Service service) {
		ServerResult result = new ServerResult();
		if (service == null || StringUtils.isBlank(nodeId)) {
			result.setFailMessage("参数错误");
			return result;
		}
		service.setId(nodeId);
		try {
			serverLogic.setServiceName(service);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}
	
	private void addService(List<Service> servicePerfs, PerformanceView performance, Service newService, Map<String, Map<String, Object>> contrastMap, Map<String, Map<String, Object>> serviceSeverityMap) {
		String serviceName = null;
		String serviceIp = null;
		int servicePort = 0;
		String protocolName = null;
		int focusOrnot = 0;
		L7Module l7Module = null;
		int protocol = 0;
		int autoDiscoveryProtocol = 0;
		// 不是协议分析器上报的数据需要对应协议号
		if (!"1".equals(performance.get("agentFlag"))) {
			newService.setProtocol(80);
			newService.setAutoDiscoveryProtocol(80);
		}
		if (newService != null) {
			protocol = newService.getProtocol();
			autoDiscoveryProtocol = newService.getAutoDiscoveryProtocol();
			l7Module = l7ModuleLogic.queryL7ModuleById(newService.getProtocol() == 0
					? newService.getAutoDiscoveryProtocol() : newService.getProtocol());
			serviceName = newService.getName();
			serviceIp = newService.getIp();
			servicePort = newService.getPort();
			focusOrnot = newService.getFocus();
			if (l7Module != null) {
				protocolName = l7Module.getName();
			}
		}
		Map<String, Object> perfMap = new HashMap<String, Object>();
		if (!contrastMap.isEmpty() || !serviceSeverityMap.isEmpty()) {
			Map<String, Object> severity = serviceSeverityMap.get(performance == null ? newService.getId() : performance.getServiceId());
			if (severity != null) {
				perfMap.putAll(severity);
			}
			Map<String, Object> perf = contrastMap.get(newService.getId());
			if (perf != null) {
				perfMap.putAll(contrastMap.get(newService.getId()));
			}
		}
		servicePerfs.add(new Service(newService.getId(), serviceName, serviceIp, servicePort, protocolName,
				performance, focusOrnot, perfMap, protocol, autoDiscoveryProtocol));
	}
	
	private Map<String, Object> setCompareResult(PerformanceView perf, PerformanceView lastPerf) {
		int receive = KEEP, post = KEEP, connect = KEEP, throughput = KEEP, responseTime = KEEP, error = KEEP;
		Map<String, Object> map = new HashMap<String, Object>();
		receive = Double.parseDouble(perf.get("network/bytes/rx").toString())
				- Double.parseDouble(lastPerf.get("network/bytes/rx").toString()) > KEEP
						? UP
						: (Double.parseDouble(perf.get("network/bytes/rx").toString())
								- Double.parseDouble(lastPerf.get("network/bytes/rx").toString()) == KEEP)
										? KEEP : DOWN;
		throughput = Double.parseDouble(perf.get("system/throughput/total").toString())
				- Double.parseDouble(lastPerf.get("system/throughput/total").toString()) > KEEP
						? UP
						: (Double.parseDouble(perf.get("system/throughput/total").toString()) - Double
								.parseDouble(lastPerf.get("system/throughput/total").toString()) == KEEP)
										? KEEP : DOWN;
		responseTime = Double.parseDouble(perf.get("system/response_time/avg").toString())
				- Double.parseDouble(lastPerf.get("system/response_time/avg").toString()) > KEEP
						? UP
						: (Double.parseDouble(perf.get("system/response_time/avg").toString()) - Double
								.parseDouble(lastPerf.get("system/response_time/avg").toString()) == KEEP)
										? KEEP : DOWN;
		error = Double.parseDouble(perf.get("system/error/count").toString())
				- Double.parseDouble(lastPerf.get("system/error/count").toString()) > KEEP
						? UP
						: (Double.parseDouble(perf.get("system/error/count").toString()) - Double
								.parseDouble(lastPerf.get("system/error/count").toString()) == KEEP) ? KEEP
										: DOWN;
				
		map.put("serviceId", perf.getServiceId());
		map.put("reseiveStatus", receive);
		map.put("postStatus", post);
		map.put("connect", connect);
		map.put("throughput", throughput);
		map.put("responseTime", responseTime);
		map.put("error", error);
		
		return map;
	}

	@Override
	public ServerResult queryDisService(String serviceId) {
		ServerResult result = new ServerResult();
		try {
			Service service = serverLogic.queryDisServiceById(serviceId);
			result.setNode(service);
		} catch (Exception e) {
			ExceptionUtils.error(logger, "queryDisService 失败", e);
			result.setFailMessage("查询服务节点失败");
		}

		return result;
	}

	@Override
	public ServerResult updateServiceIps(String appId, String nodeId, Service service) {
		ServerResult result = new ServerResult();
		if (service == null || StringUtils.isBlank(nodeId)) {
			result.setFailMessage("参数错误");
			return result;
		}
		service.setId(nodeId);
		try {
			Service serv = serverLogic.updateServiceIps(appId, service);
			result.setNode(serv);
		} catch (Exception e) {
			result.setFailMessage("过滤节点IP失败");
		}
		return result;
	}

	@Override
	public Result saveLuaSettings(LuaSettings settings) {
		Result result = new Result();
		if(StringUtils.isBlank(settings.getServiceId())){
			result.setFailMessage("参数不能为空！");
			return result;
		}
		result = serverLogic.saveLuaSettings(settings);
		return result;
	}

	@Override
	public Result queryLuaSettings(String serviceId) {
		Result result = new Result();
		if(StringUtils.isBlank(serviceId)){
			result.setFailMessage("参数不能为空！");
			return result;
		}
		result = serverLogic.queryLuaSettings(serviceId);
		return result;
	}
}
